package cn.zf233.jwtshiro.web;

import cn.zf233.jwtshiro.common.R;
import cn.zf233.jwtshiro.entity.User;
import cn.zf233.jwtshiro.service.UserService;
import cn.zf233.jwtshiro.util.JWTUtil;
import cn.zf233.jwtshiro.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zf233 on 2021/7/12
 */
@RestController
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R<String> login(User user) {

        User result = userService.login(user.getUsername(), user.getPassword());
        if (result != null) {
            result.setPassword(null);
            Map<String, Object> loadMap = new HashMap<>(1);
            loadMap.put("user", JsonUtil.toJson(result));
            String token = JWTUtil.getToken(loadMap);
            return R.createBySuccess("登陆成功", token);
        }
        return R.createByErrorMessage("登陆失败");
    }

    @GetMapping("/hello")
    public R<String> hello(String token) {
        User user = super.loadUser(token);
        String s = JsonUtil.toJson(user);
        System.out.println(s);
        return R.createBySuccessMessage("欢迎：" + JsonUtil.toJson(user));
    }
}
